package com.jindi.appuser.util;

import org.dom4j.DocumentHelper;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;


/**
 * xml工具类
 * @author miklchen
 *
 */
public class XMLUtil {
	
	/**
	 * 解析xml,返回第一级元素键值对。如果第一级元素有子节点，则此节点的值是子节点的xml数据。
	 * @param strxml
	 * @return
	 * @throws JDOMException
	 * @throws IOException
	 */
	public static Map<String, String> doXMLParse(String strxml) throws JDOMException, IOException {
		//strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");

		if(null == strxml || "".equals(strxml)) {
			return null;
		}
		
		Map<String, String> m = new HashMap<String, String>();
		
		InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(in);
		Element root = doc.getRootElement();
		List<?> list = root.getChildren();
		Iterator<?> it = list.iterator();
		while(it.hasNext()) {
			Element e = (Element) it.next();
			String k = e.getName();
			String v = "";
			List<?> children = e.getChildren();
			if(children.isEmpty()) {
				v = e.getTextNormalize();
			} else {
				v = XMLUtil.getChildrenText(children);
			}
			
			m.put(k, v);
		}
		
		//关闭流
		in.close();
		
		return m;
	}
	
	/**
	 * 获取子结点的xml
	 * @param children
	 * @return String
	 */
	public static String getChildrenText(List<?> children) {
		StringBuffer sb = new StringBuffer();
		if(!children.isEmpty()) {
			Iterator<?> it = children.iterator();
			while(it.hasNext()) {
				Element e = (Element) it.next();
				String name = e.getName();
				String value = e.getTextNormalize();
				List<?> list = e.getChildren();
				sb.append("<" + name + ">");
				if(!list.isEmpty()) {
					sb.append(XMLUtil.getChildrenText(list));
				}
				sb.append(value);
				sb.append("</" + name + ">");
			}
		}
		
		return sb.toString();
	}
	
	/**
	 * 获取xml编码字符集
	 * @param strxml
	 * @return
	 * @throws IOException 
	 * @throws JDOMException 
	 */
	public static String getXMLEncoding(String strxml) throws JDOMException, IOException {
		InputStream in = HttpClientUtil.String2Inputstream(strxml);
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(in);
		in.close();
		return (String)doc.getProperty("encoding");
	}
	
	public static String setXML(String return_code, String return_msg){
		return "<xml><return_code><![CDATA[" + return_code + "]]></return_code>"
				+ "<return_msg><![CDATA[" + return_msg + "]]></return_msg></xml>";
	}
	
	public static String mapToXml(Map<?, ?> map){
		StringBuffer sb = new StringBuffer();
		
		sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><xml>");
		
		mapToXML2(map,sb);
		
		sb.append("</xml>");
		
		return sb.toString();
	}
	
	public static void mapToXML2(Map<?, ?> map,StringBuffer sb){
		Set<?> set = map.keySet();
		for(Iterator<?> it = set.iterator(); it.hasNext();){
			String key = (String) it.next();
			Object value = map.get(key);
			if(null == value){
				value = "";
			}
			if(value.getClass().getName().equals("java.util.ArrayList")){
				ArrayList<?> list = (ArrayList<?>)map.get(key);
				sb.append("<" + key + ">");
				for(int i = 0; i < list.size(); i++){
					HashMap<?, ?> hm = (HashMap<?, ?>) list.get(i);
					mapToXML2(hm, sb);
				}
				sb.append("</" + key + ">");
			}else{
				if(value instanceof HashMap){
					sb.append("<" + key + ">");
					mapToXML2(map, sb);
					sb.append("</" + key + ">");
				}else{
					sb.append("<" + key + ">" + value + "</" + key + ">");
				}
			}
		}
	}
	/** 
     * @description 将xml字符串转换成map 
     * @param xml 
     * @return Map 
     */  
    public static Map<String,String> readStringXmlOut(String xml) {  
        Map<String,String> map = new HashMap<String,String>();  
        org.dom4j.Document doc = null;  
        try {  
            doc = DocumentHelper.parseText(xml); // 将字符串转为XML 
            org.dom4j.Element rootElt = doc.getRootElement(); // 获取根节点  
            @SuppressWarnings("unchecked")
			List<Element> list = rootElt.elements();//获取根节点下所有节点  
            for (Element element : list) {  //遍历节点  
                map.put(element.getName(), element.getText()); //节点的name为map的key，text为map的value  
            }  
        } catch (org.dom4j.DocumentException e) {  
            e.printStackTrace();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return map;  
    }  
}
